package com.joker.aigc.jsonconvert.controller;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Assert;
import com.joker.aigc.domain.entity.R;
import com.joker.aigc.jsonconvert.domain.bo.JsonToSqlBo;
import com.joker.aigc.jsonconvert.domain.dto.JsonDataResultDTO;
import com.joker.aigc.jsonconvert.domain.dto.JsonMappingSqlDTO;
import com.joker.aigc.jsonconvert.service.JsonConvertService;
import com.joker.aigc.utils.JsonToSqlUtils;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: feixiang.li
 * @date: 2025-01-24 16:38
 */
@Slf4j
@RestController
@RequestMapping("/api/1.0/tools/json")
public class JsonFileConvertController {


    @Autowired
    private JsonConvertService jsonConvertService;


    /**
     * json文件转换sql文件
     *
     * @param file        文件
     * @param jsonToSqlBo
     * @param response
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/convert", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public void jsonToSql(
            @RequestPart("file") MultipartFile file,
            @RequestPart("data") JsonToSqlBo jsonToSqlBo,
            HttpServletResponse response) throws IOException {

        Assert.notNull(file, "文件不能为空");
        Assert.notNull(jsonToSqlBo, "jsonToSqlBo参数不能为空");
        log.info("json转换参数:{}", jsonToSqlBo);
        jsonToSqlBo.setMultipartFile(file);
        File convert = jsonConvertService.convert(jsonToSqlBo);
        // 设置响应头，控制浏览器下载该文件
        String filename = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
        response.setContentLength((int) convert.length());

        try (FileInputStream fileInputStream = new FileInputStream(convert);
             ServletOutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
        }

    }


    /**
     * 获取json字段名
     *
     * @param file
     * @return
     */
    @PostMapping(value = "/getFieldName", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public R<JsonDataResultDTO> getFieldName(
            @RequestPart("file") MultipartFile file
    ) {
        try {
            File file1 = File.createTempFile("temp", ".json");
            file.transferTo(file1);
            List<JsonMappingSqlDTO> jsonMappingSqlDTOList = JsonToSqlUtils.getJsonMappingSqlDTOList(file1);
            log.info("jsonMappingSqlDTOList:{}", jsonMappingSqlDTOList);
            JsonDataResultDTO jsonDataResultDTO = new JsonDataResultDTO();
            jsonDataResultDTO.setSqlDTOList(jsonMappingSqlDTOList);
            jsonDataResultDTO.setData(JsonToSqlUtils.getData(file1, jsonMappingSqlDTOList));
            jsonDataResultDTO.setTableColumns(jsonMappingSqlDTOList.stream().map(JsonMappingSqlDTO::getFrom).collect(Collectors.toList()));
            jsonDataResultDTO.setSuccess(true);
            return R.ok(jsonDataResultDTO);
        } catch (Exception e) {
            log.error("获取json字段名失败", e);
            JsonDataResultDTO jsonDataResultDTO = new JsonDataResultDTO();
            jsonDataResultDTO.setData(new ArrayList<>());
            jsonDataResultDTO.setSqlDTOList(new ArrayList<>());
            jsonDataResultDTO.setTableColumns(new ArrayList<>());
            jsonDataResultDTO.setSuccess(false);
            return R.error(jsonDataResultDTO);
        }
    }


    /**
     * 将json文件转换成正确的文件
     *
     * @param multipartFile
     * @return
     */
    @PostMapping(value = "/convertToTrue", consumes = MediaType.MULTIPART_FORM_DATA_VALUE )
    public ResponseEntity<Resource> convertToTrue(@RequestParam("file") MultipartFile multipartFile,HttpServletResponse response)  {
        File error = null;
        File to = null;
        try {

            error = File.createTempFile("temp", ".json");
            multipartFile.transferTo(error);
            to = File.createTempFile("too", ".json");
            File convert = JsonToSqlUtils.convertValidSql(error, to);
            // 设置响应头，控制浏览器下载该文件
            String filename = DateUtil.format(DateUtil.date(), "yyyy-MM-dd HH:mm:ss") + ".json";
            log.info("文件名:{}", filename);

            // 文件路径
            Path filePath = Paths.get(convert.getPath()).toAbsolutePath().normalize();
            Resource resource = new UrlResource(filePath.toUri());
            // 设置HTTP头信息
            return ResponseEntity.ok()
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    // 或者根据文件类型设置，例如MediaType.parseMediaType("application/pdf")
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
                    .body(resource);
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
//            response.setContentLength((int) convert.length());
//
//            try (FileInputStream fileInputStream = new FileInputStream(convert);
//                 ServletOutputStream outputStream = response.getOutputStream()) {
//
//                byte[] buffer = new byte[1024];
//                int bytesRead;
//                while ((bytesRead = fileInputStream.read(buffer)) != -1) {
//                    outputStream.write(buffer, 0, bytesRead);
//                }
//            }

        } catch (Exception e) {
            log.error("将json文件转换成正确的文件失败", e);
            FileUtil.del(error);
            FileUtil.del(to);
        }

        return ResponseEntity.ok().build();
    }

}
